//
//  TestViewController3.swift
//  demo01
//
//  Created by babybus on 2025/6/26.
//
import UIKit
//struct colorInfo{
//    var ColorName:String
//    var ColorType:UIColor
//    var showBorder:Bool
//}

class ColorBlockTest: UIViewController,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout{
    private var collectionView:UICollectionView!
    private var stackView:UIStackView!
    private var items:[ColorInfo]=[]
    private var numsOfRow = 3
    private var longPressGesture:UILongPressGestureRecognizer!
    
    
    override func viewDidLoad() {
        self.navigationController?.navigationBar.backgroundColor = .white
        self.navigationItem.title = "颜色测试"
        
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .vertical
        collectionView = UICollectionView(frame: view.bounds, collectionViewLayout: layout)
        collectionView.backgroundColor = .white
        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.register(ColorCell.self, forCellWithReuseIdentifier: "ColorCell")
        collectionView.register(MyHeaderView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "MyHeader")
        let color1 = ColorInfo(ColorName: "红色", ColorType: .red, showBorder: false)
        let color2 = ColorInfo(ColorName: "蓝色", ColorType: .blue, showBorder: false)
        let color3 = ColorInfo(ColorName: "绿色", ColorType: .green, showBorder: false)
        let color4 = ColorInfo(ColorName: "黄色", ColorType: .yellow, showBorder: false)
        let color5 = ColorInfo(ColorName: "粉色", ColorType: .systemPink, showBorder: false)
        let color6 = ColorInfo(ColorName: "橙色", ColorType: .orange, showBorder: false)
        items.append(color1)
        items.append(color2)
        items.append(color3)
        items.append(color4)
        items.append(color5)
        items.append(color6)
        
        let tableBtn = MyButton()
        tableBtn.configure(title: "按钮1", titleFor: .normal,titleColor: .black, titleColorFor: .normal,backgroundColor: .green)
        tableBtn.addTarget(self, action: #selector(changeLayout), for: .touchUpInside)
        
        let tableBtn2 = MyButton()
        tableBtn2.configure(title: "按钮2", titleFor: .normal,titleColor: .black, titleColorFor: .normal,backgroundColor: .blue)
        tableBtn2.addTarget(self, action: #selector(changecolor), for: .touchUpInside)
        
        let tableBtn3 = MyButton()
        tableBtn3.configure(title: nil, titleFor: .normal,titleColor: .black, titleColorFor: .normal,backgroundColor: .yellow)
        tableBtn3.setImage(UIImage(systemName: "plus"), for: .normal)
        tableBtn3.addTarget(self, action: #selector(addTotail), for: .touchUpInside)
        
        let tableBtn4 = MyButton()
        tableBtn4.configure(title: nil, titleFor: .normal, titleColor: .black, titleColorFor: .normal, backgroundColor: .orange)
        tableBtn4.setImage(UIImage(systemName: "minus"), for: .normal)
        tableBtn4.addTarget(self, action: #selector(addToRandom), for: .touchUpInside)
        
        longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(delColorBlock(_:)))
        collectionView.addGestureRecognizer(longPressGesture)
        
        let buttonStackView = UIStackView()
        buttonStackView.axis = .horizontal
        buttonStackView.spacing = 8
        buttonStackView.alignment = .fill
        buttonStackView.distribution = .fillEqually
        view.addSubview(buttonStackView)
        view.addSubview(collectionView)
        
        [tableBtn, tableBtn2, tableBtn3, tableBtn4].forEach {
            buttonStackView.addArrangedSubview($0)
            $0.snp.makeConstraints { make in
                make.height.equalTo(50)
            }
        }
        buttonStackView.snp.makeConstraints { make in
            make.leading.trailing.equalToSuperview().inset(20)
            make.bottom.equalToSuperview().inset(20)
        }
        collectionView.snp.makeConstraints { make in
            make.top.equalToSuperview()
            make.left.right.equalToSuperview()
            make.bottom.equalTo(buttonStackView.snp.top).offset(-20)
        }
        view.backgroundColor = .gray
    }
    @objc private func backAction() {
        navigationController?.popViewController(animated: true)
    }
    
                            
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        if kind == UICollectionView.elementKindSectionHeader{
            let header = collectionView.dequeueReusableSupplementaryView(
                ofKind:kind,withReuseIdentifier: "MyHeader",for: indexPath
            )as! MyHeaderView
            return header
        }
        return UICollectionReusableView();
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return items.count;
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ColorCell", for: indexPath)as! ColorCell;
        let item = items[indexPath.row]
        cell.configure(colorname: item.ColorName, colortype: item.ColorType,showBorder: item.showBorder)
        
        return cell;
    }
    
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let width = (collectionView.bounds.width - CGFloat(numsOfRow)*10.0)/CGFloat(numsOfRow);
        return CGSize(width: width, height: 100)
    }
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
        return CGSize(width: collectionView.bounds.width, height: 0)
    }
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let cell = collectionView.cellForItem(at: indexPath)as! ColorCell
        let color_name = cell.getColorName()
        print("collectionView -- 颜色 -- " + color_name)
        cell.setColorButtonBorder()
        
    }
    @objc func changeLayout(){
        if numsOfRow == 3{
            numsOfRow = 1
        }else {
            numsOfRow = 3
        }
        collectionView.reloadData()
    }
    @objc func changecolor(){
        let randomIndices = Array(0..<items.count).shuffled().prefix(3)
        for i in randomIndices{
            items[i].ColorType = getcolor()
        }
        collectionView.reloadData()
    }
    @objc func getcolor()->UIColor{
        let red = CGFloat.random(in: 0...1)
        let green = CGFloat.random(in: 0...1)
        let blue = CGFloat.random(in: 0...1)
        return UIColor(red:red,green:green,blue:blue,alpha: 1.0)
    }
    func getNewColorBlock()->ColorInfo{
        let randomColor = getcolor()
        let itemTemp = ColorInfo(ColorName: "随机", ColorType: randomColor, showBorder: false)
        return itemTemp
    }
    @objc func addTotail(){
        items.append(getNewColorBlock())
        collectionView.reloadData()
    }
    @objc func addToRandom(){
        let position = Int.random(in: 0..<items.count)
        let block = getNewColorBlock()
        items.insert(block, at: position)
        collectionView.reloadData()
    }
    @objc func delColorBlock(_ gesture:UILongPressGestureRecognizer){
        print("delColorBlock")
        guard  gesture.state == .began else {return}
        let positionForGesture = gesture.location(in: collectionView)
        guard let index = collectionView.indexPathForItem(at: positionForGesture) else {return}
        confirmToDel(index:index)
    }
    func confirmToDel(index:IndexPath){
        print("confirmToDel")
        let alert = UIAlertController(title: "删除", message: "确定删除这个颜色块吗？", preferredStyle: .alert)
        let delAction = UIAlertAction(title: "删除", style: .destructive,handler: {action in
            self.delActionFinally(withParameter: index)
        })
        let cancelAction = UIAlertAction(title: "取消", style: .cancel)
        alert.addAction(delAction)
        alert.addAction(cancelAction)
        
        present(alert, animated: true)
    }
    func delActionFinally(withParameter index: IndexPath) {
        items.remove(at: index.row)
        collectionView.reloadData()
    }
}
